package main

import (
	"github.com/boltdb/bolt"
	"fmt"
	"match-spider/util/boltdb"
	"strings"
	"encoding/json"
	"regexp"
	"strconv"
	"github.com/xuri/excelize"
	"time"
)
/**
预测球队最终得分所需数据
 */
/**
t1 主队
t2 客队
 */
func formatData(league string,startAt string,t1 string,t2 string,text string)(float64,float64)  {
	jsonMap:=make(map[string]interface{})
	json.Unmarshal([]byte(text),&jsonMap)
	nearInfo:=jsonMap["NearInfo"].(map[string]interface{})
	guestInfo:=nearInfo["GuestInfo"].([]interface{})
	homeInfo:=nearInfo["HomeInfo"].([]interface{})
	reg, _ := regexp.Compile("\\[[\\S\\s]+?]")
	//主队
	t1= reg.ReplaceAllString(t1, "")
	//客队
	t2= reg.ReplaceAllString(t2, "")
	//主客同场的比赛
	//时间间隔不超过6个月

	homeMatch:=make([]map[string]float64,0)
	guestMatch:=make([]map[string]float64,0)

	for _,v:=range homeInfo{
		m:=v.(map[string]interface{})
		time1,_:=time.Parse("20060102150405",m["MatchTimeStr"].(string))
		time2,_:=time.Parse("06-01-02 15:04",startAt)
		if m["SclassName"]==league&&time2.Sub(time1).Hours()<24*30*6&&m["HomeTeam"]==t1{
			data:=map[string]float64{
				"homeScore":m["HomeScore"].(float64),
				"guestScore":m["GuestScore"].(float64),
			}
			homeMatch=append(homeMatch,data)
		}
	}
	for _,v:=range guestInfo{
		m:=v.(map[string]interface{})
		time1,_:=time.Parse("20060102150405",m["MatchTimeStr"].(string))
		time2,_:=time.Parse("06-01-02 15:04",startAt)
		if m["SclassName"]==league&&time2.Sub(time1).Hours()<24*30*6&&m["GuestTeam"]==t2{
			data:=map[string]float64{
				"homeScore":m["HomeScore"].(float64),
				"guestScore":m["GuestScore"].(float64),
			}

			guestMatch=append(guestMatch,data)
		}
	}
	size1:=len(homeMatch)
	size2:=len(guestMatch)
	if size1>3&&size2>3{
		if size1>size2{
			homeMatch=homeMatch[:size2]
		}
		if size1<size2{
			guestMatch=guestMatch[:size1]
		}
		//计算平均得分
		totalA1:=float64(0)
		totalA2:=float64(0)
		totalB1:=float64(0)
		totalB2:=float64(0)
		for _,v:=range homeMatch{
			totalA1+=v["homeScore"]
			totalA2+=v["guestScore"]
		}
		for _,v:=range guestMatch{
			totalB1+=v["homeScore"]
			totalB2+=v["guestScore"]
		}
		sizeA:=float64(len(homeMatch))
		sizeB:=float64(len(guestMatch))
		scoreA1:=totalA1/sizeA
		scoreB1:=totalB1/sizeB
		return scoreA1,scoreB1
	}
	return float64(-1),float64(-1)

}
/**
终盘盘口平均值
去掉一个最大值和最小值
 */
func odds(data string) float64{
	s:=strings.Split(data,"!")
	i:=float64(0)
	score:=make([]float64,0)
	total:=float64(0)
	for _,v:=range s{

		d:=strings.Split(v,"^")
		if len(d)>6{
			i++
			//val,_=strconv.ParseFloat(d[3],64)
			val,_:=strconv.ParseFloat(d[6],64)
			score=append(score,val)
		}

	}
	//获取最大值和最小值
	max:=float64(0)
	min:=float64(99)
	for _,v:=range score {
		if v>max{
			max=v
		}
		if v<min{
			min=v
		}
	}
	//计算
	hasRemoveMax:=false
	hasRemoveMin:=false
	hasRemovedCount:=float64(0)
	for _,v:=range score {
		if v==max&&!hasRemoveMax{
			hasRemoveMax=true
			hasRemovedCount++
		}else if v==min&&!hasRemoveMin{
			hasRemoveMin=true
			hasRemovedCount++
		}else{
			total+=v
		}
	}
	if i-hasRemovedCount>0{
		return total/(i-hasRemovedCount)
	}
	return float64(0)
}
func score(fn func([]interface{},int)){
	i:=0
	boltdb.ScanTx("matchs-2017", func(tx *bolt.Tx) {

		tx.ForEach(func(name []byte, b *bolt.Bucket) error {
			b.ForEach(func(k, v []byte) error {
				content:=string(v)
				s:=strings.Split(content,"^")

				league:=s[1]
				startAt:=s[2]
				t1:=s[3]
				t2:=s[5]
				s1,_:=strconv.ParseInt(s[4],10,64)
				s2,_:=strconv.ParseInt(s[6],10,64)
				totalScore:=s1+s2
				boltdb.Get("overunder-2017",league,string(k), func(data string) {
					//if strings.Contains(data,"澳门"){

						boltdb.Get("lastmatch-2017",league,string(k), func(text string) {


							if strings.Index(text,"BaseInfo")>0{
								s1,s2:=formatData(league,startAt,t1,t2,text)
								if s1>=0&&s2>=0{

									ss:=odds(data)
									if ss>0{
										i++
										slice:=[]interface{}{string(k),s1,s2,ss,totalScore}
										fmt.Println(slice)
										fn(slice,i)
									}

								}

							}else{

							}

						})


				})
				return nil
			})
			return nil
		})

	})
	fmt.Println(i)
}

func main()  {
	e:=[]string{"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"}
	xlsx := excelize.NewFile()

	categories := []string{
		"id",
		"主队平均得分",
		"客队平均得分",
		"盘口均值",
		"实际总得分",
	}
	for k,v:=range categories{
		len:=int(k/26)
		s:=""
		if len>0{
			s+=e[len-1]+e[k%26]
		}else{
			s+=e[k%26]
		}

		xlsx.SetCellValue("Sheet1",s+"1", v)
	}
	score(func(s []interface{}, i int) {
		for k,v:=range s{
			len:=int(k/26)
			s:=""
			if len>0{
				s+=e[len-1]+e[k%26]
			}else{
				s+=e[k%26]
			}
			xlsx.SetCellValue("Sheet1",s+strconv.Itoa(i+1), v)
		}
	})
	err := xlsx.SaveAs("./Workbook.xlsx")
	if err != nil {
		fmt.Println(err)
	}

}
